package com.xiaode.plugin.influx;

import cn.hutool.core.util.StrUtil;

import com.influxdb.client.DeleteApi;
import com.influxdb.client.InfluxDBClient;
import com.influxdb.client.InfluxDBClientFactory;
import com.influxdb.client.WriteApi;
import com.influxdb.client.domain.WritePrecision;
import com.influxdb.query.FluxTable;
import com.xiaode.common.model.dto.log.AdminLogDTO;
import com.xiaode.common.model.dto.log.UserSLogDTO;
import com.xiaode.common.model.dto.log.UserTLogDTO;
import org.apache.commons.collections4.map.HashedMap;
import java.time.OffsetDateTime;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

public class InfluxDbKit {

	/**
	 * 插入一行信息 同步
	 */
//	public static void insertSyn(Object log) throws Exception {
//		WriteApiBlocking writeApi = InFluxDbPlugin.influxDB.getWriteApiBlocking();
//		writeApi.writeMeasurement(WritePrecision.S, log);
//	}
	
	/**
	 * 插入一行日志信息 异步
	 */
	public static void insertAsyn(AdminLogDTO log) {
		try (WriteApi writeApi = InFluxDbPlugin.influxDB.makeWriteApi()) {
			writeApi.writeMeasurement(WritePrecision.S, log);
		}catch (Exception e) {
			e.printStackTrace();
		}
	}
	public static void insertAsyn(UserSLogDTO log) {
		try (WriteApi writeApi = InFluxDbPlugin.influxDB.makeWriteApi()) {
			writeApi.writeMeasurement(WritePrecision.S, log);
		}catch (Exception e) {
			e.printStackTrace();
		}
	}
	public static void insertAsyn(UserTLogDTO log) {
		try (WriteApi writeApi = InFluxDbPlugin.influxDB.makeWriteApi()) {
//			writeApi.writeMeasurement(WritePrecision.S, log);
		}catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 插入多行信息 同步
	 */
//	public static void insertsSyn(List<Object> logs) throws Exception {
//		WriteApiBlocking writeApi = InFluxDbPlugin.influxDB.getWriteApiBlocking();
//		writeApi.writeMeasurement(WritePrecision.S, logs);
//	}
	
	/**
	 * 插入多行日志信息 异步
	 */
//	public static void insertsAsyn(List<Object> logs) throws Exception {
//		try (WriteApi writeApi = InFluxDbPlugin.influxDB.makeWriteApi()) {
//			writeApi.writeMeasurement(WritePrecision.S, logs);
//		}catch (Exception e) {
//			throw e;
//		}
//	}
	
	/**
	 * 通过时间范围删除
	 * OffsetDateTime start = OffsetDateTime.now().minus(1, ChronoUnit.HOURS);
     * OffsetDateTime stop = OffsetDateTime.now();
	 */
	public static void delete(OffsetDateTime start, OffsetDateTime stop, String predicate) throws Exception {
		DeleteApi deleteApi = InFluxDbPlugin.influxDB.getDeleteApi();
		deleteApi.delete(start, stop, predicate, InFluxDbPlugin.getInfluxDbbucket(), InFluxDbPlugin.getInfluxDborg());
	}
	
	/**
	 * 通过时间范围查询
	 */
	public static List<AdminLogDTO> dbQuery(String tableName, String start, String stop) throws Exception {
		StringBuffer buffer = new StringBuffer();
		appendCommonFlux(buffer, InFluxDbPlugin.getInfluxDbbucket(), tableName, start, stop);
		appendTruncateTimeColumn(buffer, "1s");
		appendGroupFlux(buffer);
		appendSortFlux(buffer, true, "_time");
		return InFluxDbPlugin.influxDB.getQueryApi().query(buffer.toString(), AdminLogDTO.class);
	}
	
	/**
	 * 查询用户在某个时间范围内的使用时长(1m)
	 */
	public static int statisticsUseTime(String tableName, Integer userId, String start, String stop) throws Exception {
		StringBuffer buffer = new StringBuffer();
		appendCommonFlux(buffer, InFluxDbPlugin.getInfluxDbbucket(), tableName, start, stop);
		Map<String, Object> map = new HashedMap<String, Object>();
		map.put("userId", userId+"");
		map.put("_field", "modularType");
		appendFilterFlux(buffer, map, "==", "and");
		appendAggregateWindowFlux(buffer, "1m", "count", false);
		appendCountFlux(buffer);
		appendRenameFlux(buffer, "_value", "count");
		appendDropFlux(buffer, "_start","_stop","_field","_measurement");
		appendYieldFlux(buffer, "res");
		List<FluxTable> tables = InFluxDbPlugin.influxDB.getQueryApi().query(buffer.toString());

        int count = 0;
		if (tables != null && tables.size()>0){
			if (tables.get(0).getRecords()!= null && tables.get(0).getRecords().size() > 0 ){
				Long count1 = (Long) tables.get(0).getRecords().get(0).getValueByKey("count");
				count = count1.intValue();
			}
		}
		return count;
	}
	
	/**
	 * 查询每个用户在某个时间范围内的使用时长(1m)
	 */
	public static Map<String, Integer> statisticsAllUseTime(String tableName, String start, String stop) throws Exception {
		StringBuffer buffer = new StringBuffer();
		appendCommonFlux(buffer, InFluxDbPlugin.getInfluxDbbucket(), tableName, start, stop);
		Map<String, Object> map = new HashedMap<String, Object>();
		map.put("_field", "modularType");
		appendFilterFlux(buffer, map, "==", "and");
		appendAggregateWindowFlux(buffer, "1m", "count", false);
		appendCountFlux(buffer);
		appendRenameFlux(buffer, "_value", "count");
		appendDropFlux(buffer, "_start","_stop","_field","_measurement");
		appendYieldFlux(buffer, "res");
		List<FluxTable> tables = InFluxDbPlugin.influxDB.getQueryApi().query(buffer.toString());
		
		Map<String, Integer> userTime = new HashedMap<String, Integer>();
		if(tables != null && tables.size()>0) {
			for(FluxTable ft : tables) {
				if(ft.getRecords().size()>0) {
					String userId = (String) ft.getRecords().get(0).getValueByKey("userId");
					int count = (int) ft.getRecords().get(0).getValueByKey("count");
					userTime.put(userId, count);
				}
			}
		}
		return userTime;
	}
	
	/**
	 * 查询时间范围内的在线使用人数
	 */
	public static int[] statisticsTimeUse(String tableName, String start, String stop) throws Exception {
		StringBuffer buffer = new StringBuffer();
		appendCommonFlux(buffer, InFluxDbPlugin.getInfluxDbbucket(), tableName, start, stop);
		Map<String, Object> map = new HashedMap<String, Object>();
		map.put("_field", "modularType");
		appendFilterFlux(buffer, map, "==", "and");
		appendGroupFlux(buffer, "_measurement");
		appendDropFlux(buffer, "_start","_stop","_field","_measurement","_time","_value");
		appendDistinctFlux(buffer, "userId");
		//appendCountFlux(buffer);
		appendRenameFlux(buffer, "_value", "userId");
		appendYieldFlux(buffer, "res");
		List<FluxTable> tables = InFluxDbPlugin.influxDB.getQueryApi().query(buffer.toString());
		int[] array = null;
		if(tables != null && tables.size()>0) {
			if(tables.get(0).getRecords() != null && tables.get(0).getRecords().size() > 0) {
				array =  new int[tables.get(0).getRecords().size()];
				for(int i=0; i < tables.get(0).getRecords().size(); i++){
					int userId = Integer.valueOf((String) tables.get(0).getRecords().get(i).getValueByKey("userId"));
					array[i] = userId;

				}
			}
		}
		return array;
	}
	
	/**
	 * 查询时间范围内所有学生某个模块的使用时长
	 */
	public static Map<String, Integer> statisticsAllUseModularTime(String tableName, String start, String stop, List<Object> mod) throws Exception {
		StringBuffer buffer = new StringBuffer();
		appendCommonFlux(buffer, InFluxDbPlugin.getInfluxDbbucket(), tableName, start, stop);
		Map<String, Object> map = new HashedMap<String, Object>();
		map.put("_field", "modularType");
		appendFilterFlux(buffer, map, "==", "and");
		appendAggregateWindowFlux(buffer, "1m", "count", false);
		appendFilterFlux(buffer, mod, "==", "and", "_value");
		appendCountFlux(buffer);
		appendRenameFlux(buffer, "_value", "count");
		appendDropFlux(buffer, "_start","_stop","_field","_measurement");
		appendYieldFlux(buffer, "res");
		List<FluxTable> tables = InFluxDbPlugin.influxDB.getQueryApi().query(buffer.toString());
		
		Map<String, Integer> useModularTime = new HashedMap<String, Integer>();
		if(tables != null && tables.size()>0) {
			for(FluxTable ft : tables) {
				if(ft.getRecords().size()>0) {
					String userId = (String) ft.getRecords().get(0).getValueByKey("userId");
					Long count = (Long) ft.getRecords().get(0).getValueByKey("count");

					useModularTime.put(userId, count.intValue());
				}
			}
		}
		return useModularTime;
	}
	
	
	
	/**
	 * 通用表达式
	 * @param buffer
	 * @param bucketName 名称
	 * @param tableName 表名
	 * @param start 开始时间
	 * @param stop 结束时间
	 * 
	 */
	protected static void appendCommonFlux(StringBuffer buffer, String bucketName, String tableName, String start, String stop) {
		appendBucketFlux(buffer, bucketName);
		appendTimeRangeFlux(buffer, start, stop);
		appendTableFlux(buffer, tableName);
//		if(timestampFlag) {
//			appendTimestampFlux(buffer);
//		}
//		if(dropDefaultFlag) {
//			appendDropFlux(buffer);
//		}
		
	}
	
	
	/**
	 * 数据源(桶)表达式
	 * @param buffer
	 * @param bucketName 名称
	 */
	protected static void appendBucketFlux(StringBuffer buffer, String bucketName) {
		buffer.append("from(bucket: \""+bucketName+"\") ");
	}
	
	/**
	 * 表名表达式
	 * @param buffer
	 * @param tableName 名称
	 */
	protected static void appendTableFlux(StringBuffer buffer, String tableName) {
		buffer.append("|> filter(fn: (r) => r._measurement == \""+tableName+"\") ");
	}
	
	
	/**
	 * 时间范围表达式
	 * @param buffer
	 * @param start 开始时间
	 * @param stop 结束时间
	 */
	protected static void appendTimeRangeFlux(StringBuffer buffer,  String start, String stop) {
		if(StrUtil.isBlank(start)) {
			start = "1970-01-01T00:00:00.000Z";
		}
		if(StrUtil.isBlank(stop)) {
			buffer.append("|> range(start:" + start + ") ");
		}else {
			buffer.append("|> range(start:" + start + ", stop:"+ stop +") ");
		}
	}
	
	/**
	 * 删除字段表达式 
	 * @param buffer
	 * @param args 需要删除的字段【 参数为空的话删除host字段】
	 */
	protected static void appendDropFlux(StringBuffer buffer,  String... args) {
		if(args.length == 0) {
			buffer.append("|> drop(columns: [\"host\"]) ");
			return ;
		}
		buffer.append("|> drop(columns: [");
		for(int i = 0; i <  args.length; i++) {
			if(i != 0) {
				buffer.append(",");
			}
			buffer.append("\""+args[i]+"\"");
		}
		buffer.append("]) ");
	}
	
	/**
	 * 复制属性列表达式
	 * @param buffer
	 * @param oldField 原来的字段名称
	 * @param newField 新的字段名称
	 */
	protected static void appendDuplicateFlux(StringBuffer buffer,  String oldField, String newField) {
		buffer.append("|> duplicate(column: \""+oldField+"\", as: \""+newField+"\") ");
	}
	
	/**
	 * 重命名属性列表达式
	 * @param buffer
	 * @param oldField 原来的字段名称
	 * @param newField 新的字段名称
	 */
	protected static void appendRenameFlux(StringBuffer buffer,  String oldField, String newField) {
		buffer.append(" |> rename(columns: {"+oldField+": \""+newField+"\"}) ");
	}
	
	
	/**
	 * 最新一条数据表达式
	 * @param buffer
	 */
	protected static void appendLastFlux(StringBuffer buffer) {
		buffer.append("|> last() ");
	}
	
	/**
	 * 分页查询
	 * @param buffer
	 * @param n
	 * @param offset
	 */
	protected static void appendLimitFlux(StringBuffer buffer, int n, int offset) {
		buffer.append("|> limit(n:"+n+", offset: "+offset+") ");
	}
	
	/**
	 * 分组表达式
	 * @param buffer
	 */
	protected static void appendGroupFlux(StringBuffer buffer, String ...columns) {
		if(columns.length == 0) {
			buffer.append("|> group() ");
		}else {
			buffer.append("|> group(columns:[ ");
			for(int i = 0; i < columns.length; i++) {
				if(i != 0) {
					buffer.append(",");
				}
				buffer.append("\""+columns[i]+"\"");
			}
			buffer.append("]) ");
		}
		
	}
	/**
	 * 去重表达式
	 * @param buffer
	 */
	protected static void appendDistinctFlux(StringBuffer buffer, String ...columns) {
		if(columns.length == 0) {
			buffer.append("|> dsitinct() ");
		}else {
			buffer.append("|> distinct(column:\""+columns[0]+"\") ");
		}
		
	}
	/**
	 * 总数表达式
	 * @param buffer
	 */
	protected static void appendCountFlux(StringBuffer buffer) {
		buffer.append("|> count() ");
	}
	
	/**
	 * 前几条数据
	 * @param buffer
	 * @param n
	 */
	protected static void appendTopFlux(StringBuffer buffer, int n) {
		buffer.append("|> top(n:"+n+") ");
	}
	protected static void appendBottomFlux(StringBuffer buffer, int n) {
		buffer.append("|> bottom(n:"+n+") ");
	}
	/**
	 * 排序
	 * @param buffer
	 * @param descFlag true 降序 ；false 升序
	 * @param columns
	 */
	protected static void appendSortFlux(StringBuffer buffer, boolean descFlag, String ... columns) {
		if(columns.length == 0) {
			buffer.append("|> sort(columns: [\"_value\"], desc: "+descFlag+")");
		}else {
			buffer.append("|> sort(columns:[ ");
			for(int i = 0; i < columns.length; i++) {
				if(i != 0) {
					buffer.append(",");
				}
				buffer.append("\""+columns[i]+"\"");
			}
			buffer.append("], desc: "+descFlag+") ");
		}
	}
	
	/**
	 * 转换时间戳 表达式
	 * @param buffer
	 */
	protected static void appendTimestampFlux(StringBuffer buffer) {
		buffer.append("|> map(fn:(r) => ({r with _time:(int(v:uint(v:r._time))/1000000 )})) ");
	}
	
	/**
	 * 转换时间格式表达式
	 * @param buffer
	 */
	protected static void appendTimeformatFlux(StringBuffer buffer) {
		buffer.append("|> map(fn:(r) => ({r with _time:strings.substring(v: strings.replaceAll(v: string(v: r._time), t: \"T\", u: \" \"), start: 0, end: 19)})) ");
	}

	/**
	 * 时移八小时
	 * @param buffer
	 */
	protected static void appendTimeShiftFlux(StringBuffer buffer) {
		buffer.append("|> timeShift(duration: 8h) ");
	}
//	/**
//	 * 字段名 表达式
//	 * @param buffer
//	 */
//	protected static void appendFiledFlux(StringBuffer buffer, String... args) {
//		boolean flag = true;
//		for(String arg : args) {
//			if(flag) {
//				buffer.append("|> filter(fn: (r) =>");
//				flag = false;
//			}else {
//				buffer.append(InfluxDBConst.JOIN_OR);
//			}
//			buffer.append(" r."+InfluxDBConst.FIELD_VAL+" "+InfluxDBConst.JOIN_EQUAL+" \""+arg+"\" ");
//		}
//		if(!flag) {
//			buffer.append(")  ");
//		}
//	}
	
	/**
	 * 过滤单个字符表达式
	 * @param buffer
	 * @param list 
	 * @param operator 【== != 】
	 * @param join 【and or】
	 * @param fieldName
	 */
	protected static void appendFilterFlux(StringBuffer buffer, List<Object> list, String  operator, String join, String fieldName) {
		if(list == null || list.size() == 0) {
			return ;
		}
		for(int i = 0, size = list.size(); i< size; i++) {
			if(i == 0) {
				buffer.append("|> filter(fn: (r) =>");
			}else {
				buffer.append(join);
			}
			if(list.get(i) instanceof Integer) {
				buffer.append(" r."+fieldName+" "+operator+" "+list.get(i)+" ");
			}else {
				buffer.append(" r."+fieldName+" "+operator+" \""+list.get(i)+"\" ");
			}
		}
		buffer.append(")  ");
	}
	
	/**
	 * 过滤表达式
	 * @param buffer
	 * @param map 
	 * @param operator 【== != 】
	 * @param join 【and or】
	 */
	protected static void appendFilterFlux(StringBuffer buffer, Map<String,Object> map, String  operator, String join) {
		Set<Entry<String,Object>> entrySet = map.entrySet();
		Iterator<Entry<String, Object>> iterator = entrySet.iterator();
		boolean flag = true;
		while(iterator.hasNext()) {
			Entry<String, Object> next = iterator.next();
			String key = next.getKey();
			Object value = next.getValue();
			if(flag) {
				buffer.append("|> filter(fn: (r) =>");
				flag = false;
			}else {
				buffer.append(join);
			}
			if(value instanceof Integer) {
				buffer.append(" r."+key+" "+operator+" "+value+" ");
			}else {
				buffer.append(" r."+key+" "+operator+" \""+value.toString()+"\" ");
			}
		}
		if(!flag) {
			buffer.append(")  ");
		}
		
	}
	
	/**
	 * 过滤多个字段表达式
	 * @param buffer
	 * @param list 
	 * @param innerJoin 【and or】
	 * @param operator 【== != 】
	 * @param outerJoin 【and or】
	 */
	protected static void appendMulFilterFlux(StringBuffer buffer, List<Map<String,Object>> list, String innerJoin, String  operator, String outerJoin) {
		if(list == null || list.size() == 0) {
			return ;
		}
		buffer.append("|> filter(fn: (r) => ");
		boolean outerFlag = true;
		for(int i = 0; i < list.size(); i++) {
			Map<String, Object> map = list.get(i);
			Set<Entry<String,Object>> entrySet = map.entrySet();
			Iterator<Entry<String, Object>> iterator = entrySet.iterator();
			boolean innerFlag = true;
			while(iterator.hasNext()) {
				Entry<String, Object> next = iterator.next();
				String key = next.getKey();
				Object value = next.getValue();
				if(innerFlag) {
					if(outerFlag) {
						outerFlag = false;
					}else {
						buffer.append(outerJoin);
					}
					buffer.append(" ( ");
					innerFlag = false;
				}else {
					buffer.append(innerJoin);
				}
				if(value instanceof Integer) {
					buffer.append(" r."+key+" "+operator+" "+value+" ");
				}else {
					buffer.append(" r."+key+" "+operator+" \""+value.toString()+"\" ");
				}
			}
			if(!innerFlag) {
				buffer.append(" )  ");
			}
		}
		buffer.append(" )  ");
		
	}
	
	/**
	 * 时间窗口统计
	 * @param buffer
	 * @param step 步长值【10m,1h,1d...】
	 * @param aggType 统计类型【sum,count,min,max...)
	 */
	protected static void appendAggregateWindowFlux(StringBuffer buffer, String step, String aggType, Boolean createEmpty) {
		buffer.append("|> aggregateWindow(every: "+step+", fn: "+aggType+", createEmpty: "+createEmpty+") ");
	}
	
	protected static void appendWindowFlux(StringBuffer buffer, String step) {
		buffer.append("|> window(every: "+step+") ");
	}
	
	/**
	 * 不带时间窗口统计
	 * @param buffer
	 * @param aggType 统计类型【sum,count,min,max...)
	 */
	protected static void appendAggregateFlux(StringBuffer buffer, String aggType) {
		buffer.append("|> "+aggType+"() ");
	}
	
	
	
	
	/**
	 * 多个查询结果需要指定每个输出结果名称
	 * @param buffer
	 * @param name
	 */
	protected static void appendYieldFlux(StringBuffer buffer, String name) {
		buffer.append("|> yield(name: \""+name+"\") ");
	}
	
	/**
	 * 将时间指定为某单位
	 * @param buffer
	 * @param step
	 */
	protected static void appendTruncateTimeColumn(StringBuffer buffer, String step) {
		buffer.append("|> truncateTimeColumn(unit: "+step+") ");
	}
	
	/**
	 * 导入包名
	 * @param buffer
	 * @param name 包名
	 */
	protected static void appendImportFlux(StringBuffer buffer, String name) {
		buffer.append("import \""+name+"\" ");
	}
	
	/**
	 * 过滤空值
	 * @param buffer
	 */
	protected static void appendExistsFlux(StringBuffer buffer) {
		buffer.append("|> filter(fn: (r) => exists r._value ) ");
	}
	

	/**
	 * 过滤0值
	 * @param buffer
	 */
	protected static void appendZeroFlux(StringBuffer buffer) {
		buffer.append("|> filter(fn: (r) => r._value > 0) ");
	}
	
	
	
	
//	//更新范围从最后一小时拉取数据
//	from(bucket:"example-bucket")
//	  |> range(start: -1h)
//	  |> filter(fn: (r) =>
//	    r._measurement == "cpu" and
//	    r._field == "usage_system" and
//	    r.cpu == "cpu-total"
//	  )
//	 
//	//以五分钟为间隔的窗口化数据
//	from(bucket:"example-bucket")
//	  |> range(start: -1h)
//	  |> filter(fn: (r) =>
//	    r._measurement == "cpu" and
//	    r._field == "usage_system" and
//	    r.cpu == "cpu-total"
//	  )
//	  |> window(every: 5m)
//	 
//	//聚合窗口数据
//	from(bucket:"example-bucket")
//	  |> range(start: -1h)
//	  |> filter(fn: (r) =>
//	    r._measurement == "cpu" and
//	    r._field == "usage_system" and
//	    r.cpu == "cpu-total"
//	  )
//	  |> window(every: 5m)
//	  |> mean()
//	 
//	//添加时间列到聚合函数
//	from(bucket:"example-bucket")
//	  |> range(start: -1h)
//	  |> filter(fn: (r) =>
//	    r._measurement == "cpu" and
//	    r._field == "usage_system" and
//	    r.cpu == "cpu-total"
//	  )
//	  |> window(every: 5m)
//	  |> mean()
//	  |> duplicate(column: "_stop", as: "_time")
//	 
//	//取消窗口聚合表，将所有点收集到一个无限的窗口中
//	from(bucket:"example-bucket")
//	  |> range(start: -1h)
//	  |> filter(fn: (r) =>
//	    r._measurement == "cpu" and
//	    r._field == "usage_system" and
//	    r.cpu == "cpu-total"
//	  )
//	  |> window(every: 5m)
//	  |> mean()
//	  |> duplicate(column: "_stop", as: "_time")
//	  |> window(every: inf)
//	 
//	//辅助函数(将聚合或选择器函数应用于固定的时间窗口,通过every指定窗口的持续时间)
//	from(bucket:"example-bucket")
//	  |> range(start: -1h)
//	  |> filter(fn: (r) =>
//	    r._measurement == "cpu" and
//	    r._field == "usage_system" and
//	    r.cpu == "cpu-total"
//	  )
//	  |> aggregateWindow(every: 5m, fn: mean)
	
	
	
	public static void main(String[] args) {
		InfluxDBClient influxDB = InfluxDBClientFactory.create("http://116.63.107.112:8086", "38lJVoq-_BK9A02FgiHiDvL7toafVt8Td5wsbWeEi0WnaXbxZdMbJhxbEUHTW5iCHp1NUrOxgeBX2-Bex85imA==".toCharArray(), "gaojia", "test");
		
		
//		String queryValueFlux=
//				 "from(bucket: \"%s\") " +
//				 "|> range(start: %s) " +
//				 "|> filter(fn: (r) => r._measurement == \"%s\" and r.name== \"%s\" and r._field == \"%s\") " +
//				 "|> %s";
//		List<FluxTable> tables =  influxDB.getQueryApi().query(queryValueFlux);
//		System.out.println(tables);
		
		
		StringBuffer buffer = new StringBuffer();
		appendCommonFlux(buffer, "test", "tlog", "1654859688", "1655464489");
		
		System.out.println(buffer);
		Map<String, Object> map = new HashedMap<String, Object>();
		map.put("userId", "164");
		map.put("_field", "modularType");
		appendFilterFlux(buffer, map, "==", "and");
		appendAggregateWindowFlux(buffer, "1m", "count", false);
		appendCountFlux(buffer);
		appendRenameFlux(buffer, "_value", "count");
		appendDropFlux(buffer, "_start","_stop","_field","_measurement");
		appendYieldFlux(buffer, "res");
		
		System.out.println(buffer);
		List<FluxTable> tables = influxDB.getQueryApi().query(buffer.toString());

        int count = 0;
		if (tables != null && tables.size()>0){
			if (tables.get(0).getRecords()!= null && tables.get(0).getRecords().size() > 0 ){
				Long count1 = (Long) tables.get(0).getRecords().get(0).getValueByKey("count");
				count = count1.intValue();
			}
		}
		System.out.println(count);
		
		
//		from(bucket: "zyInflux2") 
//		|> range(start:-7d) 
//		|> filter(fn: (r) => r._measurement == "slog" and r._field == "modularType") 
//		|> aggregateWindow(every: 1d, fn: count, createEmpty: false) 
//		|> rename(columns: {_value: "count"})
//		|> group(columns: ["_measurement"], mode:"by")
//		|> sum(column: "count")
//		|> yield(name: "res") 
		
//		OffsetDateTime start = OffsetDateTime.now().minus(20000, ChronoUnit.HOURS);
//		OffsetDateTime stop = OffsetDateTime.now();
//		influxDB.getDeleteApi().delete(start,stop,"","test","gaojia");


//		StringBuffer buffer = new StringBuffer();
//		appendCommonFlux(buffer, "zyInflux2", "adminlog", "1654830735", "1655176335");
//		appendTruncateTimeColumn(buffer, "1s");
//		appendGroupFlux(buffer);
//		appendSortFlux(buffer, true, "_time");
//		//appendDropFlux(buffer, "_start","_stop","_measurement");
//		
//		
//		//appendRenameFlux(buffer, "_value", "adminId");
//		
//		appendYieldFlux(buffer, "adminlog");
//		System.out.println(buffer);
////////		List<FluxTable> tables =  influxDB.getQueryApi().query(buffer.toString());
//		List<AdminLogDTO> tables = influxDB.getQueryApi().query(buffer.toString(), AdminLogDTO.class);
//		System.out.println(JSONUtil.toJsonStr(tables) );
////		tables.get(0).getRecords().forEach(record -> System.out.println(String.format("%s %s: %s %s", record.getValueByKey("_time"), record.getMeasurement(), record.getField(), record.getValue())));
////		tables.get(1).getRecords().forEach(record -> System.out.println(String.format("%s %s: %s %s", record.getValueByKey("_time"), record.getMeasurement(), record.getField(), record.getValue())));
////		tables.get(2).getRecords().forEach(record -> System.out.println(String.format("%s %s: %s %s", record.getValueByKey("_time"), record.getMeasurement(), record.getField(), record.getValue())));
//		
//		try (WriteApi writeApi = influxDB.makeWriteApi()) {
//////			UserSLogDTO log = new UserSLogDTO();
//////			log.setMethodName("12333333");
//////			log.setModularType((short)2);
//////			log.setPara("nberrsbwwe333bwsr");
//////			log.setRemortIP("127.0.0.1");
//////			log.setUrl("egwrwrhbwr/wegwegw/wegw33g");
//////			log.setUserId(12337);
//////			log.setExtras("Extras23");
//////            writeApi.writeMeasurement(WritePrecision.S, log);
//////            System.out.println(123);
////
//            AdminLogDTO alog = new AdminLogDTO();
//            alog.setMethodName("12333333");
//            alog.setAuthority("6");
//            alog.setPara("nberrsbwwe333bwsr");
//            alog.setRemortIP("127.0.0.1");
//            alog.setUrl("egwrwrhbwr/wegwegw/wegw33g");
//            alog.setAdminId("12339");
//            alog.setErrorMsg("errorMsg");
//            alog.setRemortIP("111112.2434.44");
//            alog.setTimeStamp("111112");
//            alog.setField("");
//            writeApi.writeMeasurement(WritePrecision.S, alog);
//            System.out.println(123);
//        }
		influxDB.close();
		
		
	}
	

}
